let canvas;
let stage;
let img = new Image();
let sprite;

window.onload = function () {
    canvas = document.getElementById("canvascreatejs");
    stage = new createjs.Stage(canvas);

    stage.addEventListener("stagemousedown", clickCanvas)
    stage.addEventListener("stagemousemove", moveCanvas)

    let data = {
        images: ["shader.jpg"],
        frames: {width: 20, height: 20, regX: 10, regY: 10}
    }

    sprite = new createjs.Sprite(new createjs.SpriteSheet(data));
    createjs.Ticker.setFPS(20);
    createjs.Ticker.addEventListener("tick", tick)

}

function tick(e) {
    let t = stage.getNumChildren;
    for (let i = t - 1; i > 0; i--) {
        let star = stage.getChildAt(i);
        star.vY += 2;
        star.vX += 1;
        star.x = star.vX;
        star.y = star.vY;

        star.scaleX = star.scaleY = star.scaleX + star.vS;
        star.alpha += star.vA;

        if (star.alpha <= 0 || star.y > canvas.height) {
            stage.removeChildAt(i);
        }
    }
    stage.update();
}

function clickCanvas(e) {
    addStar(Math.random() * 200 + 100, stage.mouseX, stage.mouseY, 2);
}

function moveCanvas(e) {
    addStar(Math.random() * 2 + 1, stage.mouseX, stage.mouseY, 1);
}

function addStar(count, x, y, speed) {
    for (let i = 0; i < count; i++) {
        let star = sprite.clone();
        star.x = x;
        star.y = y;
        star.alpha = Math.random() * 0.5 + 0.5;//初始透明度
        star.scaleX = star.scaleY = Math.random() + 0.3;//初始大小
        let a = Math.PI * 2 * Math.random();
        let v = (Math.random() - 0.5) * 30 * speed;
        star.vX = Math.cos(a) * v;
        star.vY = Math.sin(a) * v;

        star.vS = (Math.random() - 0.5) * 0.2;
        star.vA = -Math.random() * 0.05 - 0.01;
        stage.addChild(star);
    }
}

